package opensearchext

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strconv"
	"strings"
	"time"

	opensearchapi "github.com/opensearch-project/opensearch-go/opensearchapi"
)

// ----- API Definition -------------------------------------------------------

// CreateUser removes a document from the index.
type CreateUser func(index string, id string, o ...func(*CreateUserRequest)) (*opensearchapi.Response, error)

// CreateUserRequest configures the CreateUser API request.
type CreateUserRequest struct {
	User                    string
	Password                string
	OpendistroSecurityRoles []string
	BackendRoles            []string
	Attributes              map[string]string

	IfPrimaryTerm       *int
	IfSeqNo             *int
	Refresh             string
	Routing             string
	Timeout             time.Duration
	Version             *int
	VersionType         string
	WaitForActiveShards string

	Pretty     bool
	Human      bool
	ErrorTrace bool
	FilterPath []string

	Header http.Header

	ctx context.Context
}

var (
	headerContentType     = "Content-Type"
	headerContentTypeJSON = "application/json"
	headerOsdxsrf         = "osd-xsrf"
)

func (r CreateUserRequest) MarshalJSON() ([]byte, error) {
	crMap := make(map[string]interface{})
	crMap["User"] = r.User
	crMap["Password"] = r.Password
	crMap["OpendistroSecurityRoles"] = r.OpendistroSecurityRoles
	if len(r.BackendRoles) > 0 {
		crMap["BackendRoles"] = r.BackendRoles
	}

	return json.Marshal(crMap)
}

// Do executes the request and returns response or error.
func (r CreateUserRequest) Do(ctx context.Context, transport opensearchapi.Transport) (*opensearchapi.Response, error) {
	var (
		method string
		path   strings.Builder
		params map[string]string
	)

	method = "PUT"
	//_plugins/_security/api/internalusers/<username>
	path.Grow(1 + len("_plugins") + 1 + len("_security") + 1 + len("api") + 1 + len("internalusers") + 1 + len(r.User))
	path.WriteString("/_plugins/_security/api/internalusers/")
	path.WriteString(r.User)

	params = make(map[string]string)
	jsonBody := make(map[string]interface{})

	if r.Password != "" {
		jsonBody["password"] = r.Password

	}

	if len(r.OpendistroSecurityRoles) > 0 {
		jsonBody["opendistro_security_roles"] = r.OpendistroSecurityRoles
	}

	if len(r.BackendRoles) > 0 {
		jsonBody["backend_roles"] = r.BackendRoles
	}

	if len(r.Attributes) > 0 {

		jsonBody["attributes"] = r.Attributes
	}

	if r.IfPrimaryTerm != nil {
		params["if_primary_term"] = strconv.FormatInt(int64(*r.IfPrimaryTerm), 10)
	}

	if r.IfSeqNo != nil {
		params["if_seq_no"] = strconv.FormatInt(int64(*r.IfSeqNo), 10)
	}

	if r.Refresh != "" {
		params["refresh"] = r.Refresh
	}

	if r.Routing != "" {
		params["routing"] = r.Routing
	}

	if r.Timeout != 0 {
		params["timeout"] = formatDuration(r.Timeout)
	}

	if r.Version != nil {
		params["version"] = strconv.FormatInt(int64(*r.Version), 10)
	}

	if r.VersionType != "" {
		params["version_type"] = r.VersionType
	}

	if r.WaitForActiveShards != "" {
		params["wait_for_active_shards"] = r.WaitForActiveShards
	}

	if r.Pretty {
		params["pretty"] = "true"
	}

	if r.Human {
		params["human"] = "true"
	}

	if r.ErrorTrace {
		params["error_trace"] = "true"
	}

	if len(r.FilterPath) > 0 {
		params["filter_path"] = strings.Join(r.FilterPath, ",")
	}

	reqBody, err := json.Marshal(jsonBody)
	if err != nil {
		return nil, err
	}
	body := strings.NewReader(string(reqBody))

	req, err := newRequest(method, path.String(), body)
	if err != nil {
		return nil, err
	}
	fmt.Println("Path of query", path.String())

	if len(params) > 0 {
		q := req.URL.Query()
		for k, v := range params {
			q.Set(k, v)
		}
		req.URL.RawQuery = q.Encode()
	}
	if body != nil {
		req.Header[headerContentType] = []string{headerContentTypeJSON}
	}

	if len(r.Header) > 0 {
		if len(req.Header) == 0 {
			req.Header = r.Header
		} else {
			for k, vv := range r.Header {
				for _, v := range vv {
					req.Header.Add(k, v)
				}
			}
		}
	}

	if ctx != nil {
		req = req.WithContext(ctx)
	}

	res, err := transport.Perform(req)
	if err != nil {
		return nil, err
	}

	response := opensearchapi.Response{
		StatusCode: res.StatusCode,
		Body:       res.Body,
		Header:     res.Header,
	}

	return &response, nil
}

// WithContext sets the request context.
func (f CreateUser) WithContext(v context.Context) func(*CreateUserRequest) {
	return func(r *CreateUserRequest) {
		r.ctx = v
	}
}

// WithIfPrimaryTerm - only perform the CreateUser operation if the last operation that has changed the document has the specified primary term.
func (f CreateUser) WithIfPrimaryTerm(v int) func(*CreateUserRequest) {
	return func(r *CreateUserRequest) {
		r.IfPrimaryTerm = &v
	}
}

// WithIfSeqNo - only perform the CreateUser operation if the last operation that has changed the document has the specified sequence number.
func (f CreateUser) WithIfSeqNo(v int) func(*CreateUserRequest) {
	return func(r *CreateUserRequest) {
		r.IfSeqNo = &v
	}
}

// WithRefresh - if `true` then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` (the default) then do nothing with refreshes..
func (f CreateUser) WithRefresh(v string) func(*CreateUserRequest) {
	return func(r *CreateUserRequest) {
		r.Refresh = v
	}
}

// WithRouting - specific routing value.
func (f CreateUser) WithRouting(v string) func(*CreateUserRequest) {
	return func(r *CreateUserRequest) {
		r.Routing = v
	}
}

// WithTimeout - explicit operation timeout.
func (f CreateUser) WithTimeout(v time.Duration) func(*CreateUserRequest) {
	return func(r *CreateUserRequest) {
		r.Timeout = v
	}
}

// WithVersion - explicit version number for concurrency control.
func (f CreateUser) WithVersion(v int) func(*CreateUserRequest) {
	return func(r *CreateUserRequest) {
		r.Version = &v
	}
}

// WithVersionType - specific version type.
func (f CreateUser) WithVersionType(v string) func(*CreateUserRequest) {
	return func(r *CreateUserRequest) {
		r.VersionType = v
	}
}

// WithWaitForActiveShards - sets the number of shard copies that must be active before proceeding with the CreateUser operation. defaults to 1, meaning the primary shard only. set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1).
func (f CreateUser) WithWaitForActiveShards(v string) func(*CreateUserRequest) {
	return func(r *CreateUserRequest) {
		r.WaitForActiveShards = v
	}
}

// WithPretty makes the response body pretty-printed.
func (f CreateUser) WithPretty() func(*CreateUserRequest) {
	return func(r *CreateUserRequest) {
		r.Pretty = true
	}
}

// WithHuman makes statistical values human-readable.
func (f CreateUser) WithHuman() func(*CreateUserRequest) {
	return func(r *CreateUserRequest) {
		r.Human = true
	}
}

// WithErrorTrace includes the stack trace for errors in the response body.
func (f CreateUser) WithErrorTrace() func(*CreateUserRequest) {
	return func(r *CreateUserRequest) {
		r.ErrorTrace = true
	}
}

// WithFilterPath filters the properties of the response body.
func (f CreateUser) WithFilterPath(v ...string) func(*CreateUserRequest) {
	return func(r *CreateUserRequest) {
		r.FilterPath = v
	}
}

// WithHeader adds the headers to the HTTP request.
func (f CreateUser) WithHeader(h map[string]string) func(*CreateUserRequest) {
	return func(r *CreateUserRequest) {
		if r.Header == nil {
			r.Header = make(http.Header)
		}
		for k, v := range h {
			r.Header.Add(k, v)
		}
	}
}

// WithOpaqueID adds the X-Opaque-Id header to the HTTP request.
func (f CreateUser) WithOpaqueID(s string) func(*CreateUserRequest) {
	return func(r *CreateUserRequest) {
		if r.Header == nil {
			r.Header = make(http.Header)
		}
		r.Header.Set("X-Opaque-Id", s)
	}
}

func newRequest(method, path string, body io.Reader) (*http.Request, error) {
	return http.NewRequest(method, path, body)
}

func formatDuration(d time.Duration) string {
	if d < time.Millisecond {
		return strconv.FormatInt(int64(d), 10) + "nanos"
	}
	return strconv.FormatInt(int64(d)/int64(time.Millisecond), 10) + "ms"
}
